import {
  PlusOutlined,
  // PlusCircleFilled,
  QuestionCircleOutlined,
  // CaretRightOutlined,
  // EditFilled,
  // AppstoreAddOutlined,
  // MenuOutlined,
  // PlayCircleOutlined,
  // DeleteTwoTone,
  SearchOutlined,
} from '@ant-design/icons';
import { Button, message, Input, Drawer, Space, Tabs } from 'antd';
import React, { useState, useRef } from 'react';
import { useIntl, FormattedMessage } from 'umi';
// import ReactDOM from 'react-dom';
import moment from 'moment';
import { FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType, ColumnsState } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';
// import { LightFilter, ProFormDatePicker } from '@ant-design/pro-form';
import type { FormValueType } from './components/UpdateForm';
import UpdateForm from './components/UpdateForm';
import type { TableUserList } from './data.d';
import { queryUserList, updateRule, addRule, removeRule } from './service';
import IconsTableAdd from '../../../public/icons/icon_table/add.png';
import IconsTableBiaotou from '../../../public/icons/icon_table/biaotou.png';
import IconsTableDaoChu from '../../../public/icons/icon_table/daochu.png';
import IconsTableDaoRu from '../../../public/icons/icon_table/daoru.png';
import IconsTableDel from '../../../public/icons/icon_table/del.png';
import IconsTableMuBan from '../../../public/icons/icon_table/muban.png';
import IconsTableQiYong from '../../../public/icons/icon_table/qiyong.png';
import IconsTableReturn from '../../../public/icons/icon_table/retur.png';
// import IconsTableSearch from '../../../public/icons/icon_table/search.png';
import IconsTableStop from '../../../public/icons/icon_table/stop.png';
import IconsTableUpdate from '../../../public/icons/icon_table/update.png';
import styles from './index.less';

const { TabPane } = Tabs;
/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields: TableUserList) => {
  const hide = message.loading('正在添加');
  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('正在配置');
  try {
    await updateRule({
      name: fields.name,
      desc: fields.desc,
      key: fields.key,
    });
    hide();

    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: TableUserList[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeRule({
      key: selectedRows.map((row) => row.key),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /** 分布更新窗口的弹窗 */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);
  // 列表数量
  // const [tableLength, setTableLength] = useState<number>(0);

  const actionRef = useRef<ActionType>();
  const tableRef = useRef<any>();
  const [currentRow, setCurrentRow] = useState<TableUserList>();
  const [selectedRowsState, setSelectedRows] = useState<TableUserList[]>([]);
  // const [activekey, setActiveKey] = useState<React.Key>('tab1');
  /** 国际化配置 */
  const intl = useIntl();

  const [columnsStateMap, setColumnsStateMap] = useState<Record<string, ColumnsState>>({
    name: {
      show: false,
      order: 2,
    },
  });
  // 数组
  const columns: ProColumns<TableUserList>[] = [
    {
      title: '真实姓名',
      dataIndex: 'name',
      tip: '用户真实名称',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '身份证号',
      dataIndex: 'id',
      tip: '身份证号',
      width: 400,
      valueType: 'textarea',
      filterDropdown: () => (
        <div style={{ padding: 8 }}>
          <h2>请输入内容：</h2>
          <Input style={{ width: 188, marginBottom: 8, display: 'block' }} />
        </div>
      ),
      filterIcon: (filtered) => (
        <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />
      ),
    },
    {
      // title: '所属科室',
      title: (
        <>
          所属科室
          <QuestionCircleOutlined style={{ marginLeft: 10 }} />
        </>
      ),
      dataIndex: 'section',
      valueType: 'textarea',
    },
    {
      title: '技术科室',
      dataIndex: 'technical',
      valueType: 'textarea',
      key: 'technical',
      // filters: [
      //   { text: 'Joe', value: 'Joe' },
      //   { text: 'Jim', value: 'Jim' },
      // ],
      ellipsis: true,
    },
    {
      title: '出生日期',
      dataIndex: 'birthday',
      width: '100px',
      valueType: 'textarea',
      sorter: (a: TableUserList, b: TableUserList) =>
        moment(a.birthday).unix() - moment(b.birthday).unix(),
    },
    {
      title: '最高学历',
      dataIndex: 'education',
      valueType: 'textarea',
    },
    {
      title: '登录次数',
      dataIndex: 'login_count',
      valueType: 'textarea',
    },
    {
      title: '注册时间',
      dataIndex: 'registration_time',
      valueType: 'textarea',
    },
    {
      title: '最后登录',
      dataIndex: 'last_login_time',
      valueType: 'textarea',
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleCallNo" defaultMessage="服务调用次数" />,
      dataIndex: 'count',
      hideInTable: true,
      sorter: true,
      hideInForm: true,
      renderText: (val: number) => {
        console.log('-------->>>:', val);
        return `${val} ${intl.formatMessage({
          id: 'pages.searchTable.tenThousand',
          defaultMessage: ' 万 ',
        })}`;
      },
    },
    {
      title: '状态',
      // hideInForm: true,
      dataIndex: 'status',
      initialValue: 'all',
      filters: true,
      onFilter: true,
      valueType: 'select',
      valueEnum: {
        0: {
          text: '停用',
          status: 'Default',
        },
        1: {
          text: '启用',
          status: 'Processing',
        },
      },
    },
    {
      title: (
        <FormattedMessage id="pages.searchTable.titleUpdatedAt" defaultMessage="上次调度时间" />
      ),
      sorter: true,
      hideInTable: true,
      dataIndex: 'updatedAt',
      valueType: 'dateTime',
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        const status = form.getFieldValue('status');
        if (`${status}` === '0') {
          return false;
        }
        if (`${status}` === '3') {
          return (
            <Input
              {...rest}
              placeholder={intl.formatMessage({
                id: 'pages.searchTable.exception',
                defaultMessage: '请输入异常原因！',
              })}
            />
          );
        }
        return defaultRender(item);
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      filterDropdown: () => {
        // const width = actionRef.current?.pageInfo;
        // console.log("width:-----",width)
        // console.log("width:-----",actionRef)
        // setTableLength(
        //   columns.filter((m: any) => {
        //     return m.hideInTable !== true;
        //   }).length,
        // );
        const clientWidth = (tableRef.current.clientWidth || 1000) - 24 * 2;
        console.log('clientWidth:', clientWidth);
        // console.log('tableLength:', tableLength);
        // console.log("offsetWidth:",  tableRef.current.offsetWidth)
        // console.log("scrollWidth:",  tableRef.current.scrollWidth)
        // console.log("style.width :",  tableRef.current.style.width )
        // console.log("current :", tableRef.current)
        return (
          <div className={styles.rsh_filter} style={{ width: `${clientWidth}px` }}>
            <Space align="center">
              <SearchOutlined className={styles.rsh_search_icon} />
              <div className={styles.rsh_search_title}>搜索</div>

              {columns
                .filter((m: any) => {
                  return m.hideInTable !== true;
                })
                .map((m: any, i: number) => {
                  if (m.title === '操作') return null;
                  if (typeof m.title === 'object')
                    return <Input type="text" key={i} placeholder={`搜索所属科室`} />;
                  return <Input type="text" key={i} placeholder={`搜索${m.title}`} />;
                })}

              <Button key="primary" type="primary" className={styles.rsh_btn_search}>
                查询
              </Button>
              <Button key="primary" type="primary" className={styles.rsh_btn_cancle}>
                取消
              </Button>
            </Space>
          </div>
        );
      },
      filterIcon: (filtered) => (
        <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />
      ),
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          <FormattedMessage id="pages.searchTable.config" defaultMessage="配置" />
        </a>,
        <a key="subscribeAlert" href="https://procomponents.ant.design/">
          <FormattedMessage id="pages.searchTable.subscribeAlert" defaultMessage="订阅警报" />
        </a>,
      ],
    },
  ];

  function callback(key: string) {
    console.log(key);
  }

  return (
    <>
      <div className={styles.sysHeader}>
        <h2 className={styles.labTip}>用户中心-系统用户</h2>
        <div className={styles.btnGoBackDiv}>
          <Button className={styles.btnGoBack} key="primary" icon={<img src={IconsTableReturn} />}>
            返回
          </Button>
        </div>
      </div>
      <div className={styles.btnHeaderSelect}>
        <Tabs
          defaultActiveKey="1"
          onChange={callback}
          tabBarGutter={57}
          tabBarStyle={{ marginLeft: '25px', fontSize: '20px', fontWeight: 400, color: '#a0a0a0' }}
        >
          <TabPane tab={<span className={styles.rsh_tabpane_title}>用户信息</span>} key="1">
            <div ref={tableRef}>
              <ProTable<TableUserList, { keyWord?: string }>
                actionRef={actionRef}
                // formRef={tableRef}
                className={styles.rsh_table}
                // style={{display:"none"}}
                rowKey="key"
                // 配置列的搜索相关，false 为隐藏
                search={false}
                // search={{
                //   labelWidth: 'auto',
                // }}
                headerTitle={
                  <Space>
                    <Button
                      className={styles.icon_button_left}
                      icon={<img src={IconsTableAdd} />}
                      style={{ backgroundColor: '#53c506' }}
                    >
                      新增
                    </Button>
                    <Button
                      className={styles.icon_button_left}
                      icon={<img src={IconsTableUpdate} />}
                      style={{ backgroundColor: '#ff942c' }}
                    >
                      修改
                    </Button>
                    <Button
                      className={styles.icon_button_left}
                      icon={<img src={IconsTableMuBan} />}
                      style={{ backgroundColor: '#942cff' }}
                    >
                      模板
                    </Button>
                    <Button
                      className={styles.icon_button_left}
                      icon={<img src={IconsTableBiaotou} />}
                      style={{ backgroundColor: '#59a3ff' }}
                    >
                      表头
                    </Button>
                  </Space>
                }
                columnsStateMap={columnsStateMap}
                onColumnsStateChange={(map) => setColumnsStateMap(map)}
                // 搜索
                options={{
                  // search: false,
                  fullScreen: false, // 是否显示全屏
                  reload: false, // 是否显刷新
                  density: false, // 密度
                  setting: false, // 设置icon
                }}
                toolbar={{
                  actions: [
                    <div className={styles.right_tools}>
                      <Button
                        type="text"
                        className={styles.icon_button_right}
                        icon={<img src={IconsTableDaoRu} />}
                      >
                        导入
                      </Button>
                      <Button
                        type="text"
                        className={styles.icon_button_right}
                        icon={<img src={IconsTableDaoChu} />}
                      >
                        导出
                      </Button>
                      <Button
                        type="text"
                        className={styles.icon_button_right}
                        icon={<img src={IconsTableQiYong} />}
                      >
                        启用
                      </Button>
                      <Button
                        type="text"
                        className={styles.icon_button_right}
                        icon={<img src={IconsTableStop} />}
                      >
                        停用
                      </Button>
                      <Button
                        type="text"
                        className={styles.icon_button_right}
                        icon={<img src={IconsTableDel} />}
                      >
                        删除
                      </Button>
                    </div>,
                  ],
                }}
                toolBarRender={() => [
                  <Button
                    type="primary"
                    key="primary"
                    onClick={() => {
                      handleModalVisible(true);
                    }}
                  >
                    <PlusOutlined /> 新增1
                  </Button>,
                ]}
                request={(params, sorter, filter) => queryUserList({ ...params, sorter, filter })}
                columns={columns}
                rowSelection={{
                  onChange: (_, selectedRows) => {
                    setSelectedRows(selectedRows);
                  },
                }}
                editable={{
                  type: 'multiple',
                }}
                pagination={{
                  pageSize: 10,
                }}
              />
            </div>
          </TabPane>
          <TabPane tab={<span className={styles.rsh_tabpane_title}>字段编辑</span>} key="2">
            Content of Tab Pane 2
          </TabPane>
          <TabPane tab={<span className={styles.rsh_tabpane_title}>字段架构</span>} key="3">
            Content of Tab Pane 3
          </TabPane>
        </Tabs>
      </div>

      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="已选择" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
              &nbsp;&nbsp;
              <span>
                <FormattedMessage
                  id="pages.searchTable.totalServiceCalls"
                  defaultMessage="服务调用次数总计"
                />{' '}
                {selectedRowsState.reduce((pre, item) => pre + item.login_count, 0)}{' '}
                <FormattedMessage id="pages.searchTable.tenThousand" defaultMessage="万" />
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <FormattedMessage id="pages.searchTable.batchDeletion" defaultMessage="批量删除" />
          </Button>
          <Button type="primary">
            <FormattedMessage id="pages.searchTable.batchApproval" defaultMessage="批量审批" />
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title={intl.formatMessage({
          id: 'pages.searchTable.createForm.newRule',
          defaultMessage: '新建规则',
        })}
        width="400px"
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(value as TableUserList);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.searchTable.ruleName"
                  defaultMessage="规则名称为必填项"
                />
              ),
            },
          ]}
          width="md"
          name="name"
        />
        <ProFormTextArea width="md" name="desc" />
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<TableUserList>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<TableUserList>[]}
          />
        )}
      </Drawer>
    </>
  );
};

export default TableList;
